import React, { useState, useEffect } from 'react';
import { Row, Col, Button } from 'antd';
import { randomKey } from '../../../../utils/utils';
import services from '../../../../services/api';
import ActionItem from '../../../../components/ActionSet/ActionItem';

/**
 * @component ActionReturn 动作返回配置组件
 * @prop {Array} value 组件值
 * @prop {Function} onChange 改变值之后的回调
 * @prop {Object} variable 可被用于选择的变量对象
 * @prop {Boolean} disabled 是否只读,默认false
 */

export default function ActionReturn(props) {
  const [actions, setActions] = useState([]);
  const [options, setOptions] = useState([]);

  useEffect(() => {
    // 获取函数
    function getOptions() {
      services.action.actionList({ usage_scope_limit: 'strategy' }).then((res) => {
        if (res.code === 0) {
          setOptions(res.data);
        }
      });
    }
    getOptions();
  }, []);

  useEffect(() => {
    if (props.value && props.value.length > 0) {
      setActions(initData(props.value));
    } else {
      setActions([]);
    }
  }, [props.value]);

  function initData(data) {
    const newData = data.map((item) => {
      item.id = item.id ? item.id : randomKey();
      return item;
    });
    return newData;
  }

  //添加规则
  function addAction() {
    const action = {
      name: '',
      prior: actions.length + 1,
      enabled: true,
      id: randomKey(),
    };
    actions.push(action);
    setActions(Object.assign([], actions));
    props.onChange && props.onChange(actions);
  }

  // 修改item的value回调
  function handleChange(id, value) {
    console.log(value);
    for (let i = 0; i < actions.length; i++) {
      if (actions[i].id === id) {
        actions[i] = value;
      }
    }
    setActions(Object.assign([], actions));
    console.log('actions', actions);
    props.onChange && props.onChange(actions);
  }

  // 删除
  function del(index) {
    actions.splice(index, 1);
    setActions(Object.assign([], actions));
    props.onChange && props.onChange(actions);
  }

  // 移动
  function move(item, index, step) {
    // 下移
    if (step === 'down') {
      actions.splice(index, 1); //移除当前项
      actions.splice(index + 1, 0, item); // 在index+1处插入当前item
      // 上移
    } else if (step === 'up') {
      actions.splice(index, 1); //移除当前项
      actions.splice(index - 1, 0, item); // 在index-1处插入当前item
    }
    setActions(Object.assign([], actions));
    props.onChange && props.onChange(actions);
  }
  return (
    <div style={{ marginTop: '20px' }} className='rule-wp'>
      <Row type='flex' justify='start' gutter={10} style={{ marginBottom: '10px' }}>
        <Col>
          {!props.disabled && (
            <Button
              type='primary'
              onClick={() => {
                addAction();
              }}
              disabled={Object.keys(props.variable).length === 0}
            >
              添加返回动作
            </Button>
          )}
        </Col>
      </Row>
      <Row type='flex' justify='space-between' align='middle' gutter={10} className='rule-hd'>
        <Col span={2}>序号</Col>
        <Col span={5}>动作类型</Col>
        <Col span={5}>字段</Col>
        <Col span={5}>名单名称</Col>
        <Col span={4}>状态</Col>
        {!props.disabled && <Col span={3}>操作</Col>}
      </Row>
      {actions.map((item, index) => {
        return (
          <ActionItem
            {...props}
            value={item}
            index={index + 1}
            key={item.id}
            variable={props.variable}
            disabled={props.disabled}
            onChange={handleChange.bind(this, item.id)}
            onDel={del.bind(this, index)}
            onMove={move.bind(this, item, index)}
            len={actions.length}
            form={props.form}
            codes={props.codes}
            options={options}
            compareData={(props.compareData && props.compareData[index]) || undefined}
          />
        );
      })}
    </div>
  );
}
